package com.wdd.libhttp.http;

import com.blankj.utilcode.util.GsonUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @ProjectName: OwnTool
 * @Package: com.wdd.libbase.http
 * @ClassName: JsonConvert
 * @Description: java类作用描述
 * @Author: 王丹丹
 * @CreateDate: 2019/12/4 22:57
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/12/4 22:57
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class JsonConvert<T> {
    private Type type;
    private Class<T> clazz;

    public JsonConvert() {
    }

    public JsonConvert(Type type) {
        this.type = type;
    }

    public JsonConvert(Class<T> clazz) {
        this.clazz = clazz;
    }


    public T convertResponse(String response) throws Throwable {
        if (type == null) {
            if (clazz == null) {
                // 如果没有通过构造函数传进来，就自动解析父类泛型的真实类型（有局限性，继承后就无法解析到）
                Type genType = getClass().getGenericSuperclass();
                type = ((ParameterizedType) genType).getActualTypeArguments()[0];
            } else {
                return parseClass(response, clazz);
            }
        }

        if (type instanceof Class) {
            return parseClass(response, (Class<?>) type);
        } else {
            return parseType(response, type);
        }
    }

    private T parseClass(String response, Class<?> rawType) throws Exception {
        if (rawType == null) {
            return null;
        }

        if (rawType == String.class) {
            //noinspection unchecked
            return (T) response;
        } else if (rawType == JSONObject.class) {
            //noinspection unchecked
            return (T) new JSONObject(response);
        } else if (rawType == JSONArray.class) {
            //noinspection unchecked
            return (T) new JSONArray(response);
        } else {
            T t = (T) GsonUtils.getGson().fromJson(response, rawType);
            return t;
        }
    }

    private T parseType(String response, Type type) throws Exception {
        if (type == null) {
            return null;
        }
        // 泛型格式如下： new JsonConvert<任意JavaBean>(this)
        T t = GsonUtils.getGson().fromJson(response, type);
        return t;
    }

}
